package com.example.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.shopping.mapper.UserMapper;
import com.example.shopping.pojo.User;
import com.example.shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 操作用户的 业务 层实现
 * @author 瓶盖
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String account, String password) {
        return userMapper.selectOne(
                new QueryWrapper<User>().eq("account", account)
                        .eq("password", password)
        );
    }

    @Override
    public int register(User user) {
        // 获取当前时间作为创建/更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);
        // 在插入之前应该先判断 账号是否存在
        User u1 = userMapper.selectOne(
                new QueryWrapper<User>().eq("account", user.getAccount())
        );
        if(u1 != null){
            return -1;
        }
        // 实现注册逻辑
        return userMapper.insertUser(user);
    }

    @Override
    public boolean addBalance(int userId, int balance) {
        // 先获取 用户的 原本金额
        int b1 = userMapper.selectById(userId).getBalance();
        //在这基础上进行 ++
        User user = new User();
        user.setId(userId);
        user.setBalance(b1+balance);
        return userMapper.updateUser(user) > 0;
    }

    @Override
    public void update(User user) {
        userMapper.updateById(user);
    }

    @Override
    public List<User> list() {
        return userMapper.selectList(null);
    }

    @Override
    public void removeById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public User selectUserById(int userId) {
        return userMapper.selectById(userId);
    }
}

